package io.persimmon.core.module.calculation.instance;

import io.persimmon.core.module.calculation.Calculation;
import lombok.Getter;

import java.util.concurrent.atomic.AtomicInteger;

@Getter
public class HitRateCalculation implements Calculation<Double, Boolean> {

    private AtomicInteger hitCount = new AtomicInteger(0);
    private AtomicInteger totalCount = new AtomicInteger(0);

    @Override
    public void accept(Boolean data) {
        totalCount.addAndGet(1);
        if (data) {
            hitCount.addAndGet(1);
        }
    }

    public void accept(int total, int hit) {
        totalCount.addAndGet(total);
        hitCount.addAndGet(hit);
    }

    @Override
    public Double calculationResult() {
        if (totalCount.get() == 0) {
            return 0.0;
        }
        return (double) hitCount.get() / totalCount.get();
    }

    @Override
    public void clean() {
        hitCount.set(0);
        totalCount.set(0);
    }
}
